package com.cyb.beta.controller;

import com.cyb.beta.core.Constant;
import com.cyb.beta.model.LoginLog;
import com.cyb.beta.model.ModelEnum;
import com.cyb.beta.model.User;
import com.cyb.beta.utils.DateUtils;
import com.cyb.beta.utils.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.ext.route.ControllerBind;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

/**
 * Created by Administrator on 2015/6/9.
 */
@ControllerBind(controllerKey = "/admin", viewPath = "admin")
@ClearInterceptor(ClearLayer.ALL)
public class LoginController extends BaseController {

    @Before({SessionInViewInterceptor.class})
    public void index() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            render("index.html"); //已登录成功，跳转主页面
        } else {
            render("login.html");
        }
    }

    /**
     * 验证登陆
     */
    public void doLogin() {
        String userName = getPara("username", null);
        String passWord = getPara("password", null);
//        String validateCode = getPara("validateCode", null);
        // 验证码
//        String check = getSessionAttr(ValidateController.VALIDATE_CODE);

//        if (null == userName || null == passWord || null == validateCode) {
//            setAttr("error", Constant.INCOMPLETE_LOGIN_INFO);
//        } else if (check == null) {
//            setAttr("error", Constant.TIMEOUT_CAPTCHA_EXCEPTION);
//        } else if (check != null && validateCode != null && !check.equals(validateCode.toUpperCase())) {
//            setAttr("error", Constant.INCORRECT_CAPTCHA_EXCEPTION);
//        } else {
//            removeSessionAttr("check"); // 验证码验证完毕，清楚验证码的session
        UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord, true, getRequest().getRemoteAddr());
        // 这里可以调用 subject 做判断
        Subject subject = SecurityUtils.getSubject();
        try {
            if (!subject.isAuthenticated()) {
                subject.login(token);
            }
            // 设置日期格式，获得当前时间
            String currentDate = DateUtils.getCurrentTime();

            User loginUser = (User) subject.getPrincipal();
            // 设置登陆时间，登陆ip，登陆状态
            loginUser.set(User.LAST_LOGIN_TIME, currentDate)
                    .set(User.LAST_LOGIN_IP, StringUtils.getRemoteAddr(getRequest()))
                    .set(User.LOGIN_STATUS, ModelEnum.OnlineOrOffline.ONLINE.ordinal())
                    .set(User.LOGIN_COUNT, loginUser.getInt(User.LOGIN_COUNT) + 1)
                    .update();

            // 创建本次登陆日志
            LoginLog loginLog = new LoginLog();
            loginLog.set(LoginLog.USER_ID, loginUser.get(User.ID))
                    .set(LoginLog.LOGIN_TIME, currentDate)
                    .set(LoginLog.LOGIN_IP, getRequest().getRemoteAddr())
                    .save();

            redirect("/admin"); //登录成功，跳转主页面
            return;
        } catch (AuthenticationException e) {
            setAttr("error", Constant.LOGINFAIL);
        }
//        }
        // 登录失败，跳转登录
        redirect("/admin");
    }

    /**
     * 用户登出
     */
    public void logout() {
        User loginUser = (User) getSessionAttr(Constant.SHIRO_USER);
        loginUser.set(User.LOGIN_STATUS, ModelEnum.OnlineOrOffline.OFFLINE.ordinal()).update();
        // 设置登录日志下线时间
        LoginLog.dao.updateLogoutTime(loginUser.getLong(User.ID), loginUser.getStr(User.LAST_LOGIN_TIME));

        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        redirect("/admin");
    }
}
